package com.team24.hotel.controller;

import com.team24.hotel.domain.ParentPermission;
import com.team24.hotel.domain.Permission;
import com.team24.hotel.domain.User;
import com.team24.hotel.service.IMailService;
import com.team24.hotel.service.ParentPermissionService;
import com.team24.hotel.service.PermissionService;
import com.team24.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.List;
import java.util.Random;

@RequestMapping("/login")
@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private ParentPermissionService parentPermissionService;
    @Autowired
    private IMailService iMailService;

    private String validateCheckCode = null;

    @RequestMapping("/toLogin")
    public String emailLogin() {
        return "login";
    }

    @RequestMapping(value = "/email",method = RequestMethod.POST)
    public String emailLogin(String userEmail, String password, Model model ,HttpServletRequest req,HttpServletResponse response,String emailRememberMe){
        User user=userService.findUserByEmail(userEmail);
        HttpSession session = req.getSession();
        String msg=null;
        if (user == null) {
            msg="用户不存在";
            model.addAttribute("msg",msg);
            return "login";
        } else {
            String pwd = user.getPassword();
            if (pwd != null && pwd.equals(password)) {
                session.setAttribute("user",user);
                if(emailRememberMe==null){
                    addCookie(response,userEmail,password,"no","email");
                } else {
                    addCookie(response,userEmail,password,"yes","email");
                }
                List<ParentPermission> parentPermissionList=getOwnPermissionParent(user.getUserId());
                List<Permission> permissionList = getNoParentPermission(user.getUserId());
                session.setAttribute("parentPermissionList",parentPermissionList);
                if(permissionList!=null) req.getSession().setAttribute("permissionList",permissionList);
                return pageJudge(user,session);
            } else {
                msg="密码错误";
                model.addAttribute("msg",msg);
                return "login";
            }
        }
    }

    @RequestMapping(value = "/tel",method = RequestMethod.POST)
    public String telLogin(String userTel, String password, Model model ,HttpServletRequest req,HttpServletResponse response,String telRememberMe){
        User user = userService.findUserByTel(userTel);
        HttpSession session=req.getSession();
        String msg=null;
        if (user == null) {
            msg="用户不存在";
            model.addAttribute("msg",msg);
            return "login";
        } else {
            String pwd = user.getPassword();
            if (pwd != null && pwd.equals(password)) {
                session.setAttribute("user",user);
                if(telRememberMe==null){
                    addCookie(response,userTel,password,"no","tel");
                } else {
                    addCookie(response,userTel,password,"yes","tel");
                }
                List<ParentPermission> parentPermissionList=getOwnPermissionParent(user.getUserId());
                List<Permission> permissionList = getNoParentPermission(user.getUserId());
                session.setAttribute("parentPermissionList",parentPermissionList);
                if(permissionList!=null) req.getSession().setAttribute("permissionList",permissionList);
                return pageJudge(user,session);
            } else {
                msg="密码错误";
                model.addAttribute("msg",msg);
                return "login";
            }
        }
    }

    public List<ParentPermission> getOwnPermissionParent(String userId){
        List<ParentPermission> parentPermissionList=parentPermissionService.findByUserId(userId);
        if(parentPermissionList==null) return null;
        for (ParentPermission parentPermission:parentPermissionList
        ) {
            List<Permission> permissions=permissionService.findAllByUserIdAndParentId(userId,parentPermission.getParentPermissionId());
            parentPermission.setPermissions(permissions);
        }
        for (ParentPermission parentPermission:parentPermissionList
        ) {
            System.out.print(parentPermission.getParentPermissionName()+":");
            for (Permission permission:parentPermission.getPermissions()
            ) {
                System.out.print(permission.getPermissionName()+" ");
            }
            System.out.println();
        }
        return parentPermissionList;
    }

    public List<Permission> getNoParentPermission(String userId){
        List<Permission> permissions = permissionService.findAllNoParentByUserId(userId);
        return permissions;
    }

    public String pageJudge(User user, HttpSession session){
        String roleName=userService.findUserAndRoleNameByPrimaryKey(user.getUserId()).getRoleName();
        String frontKeyword="普通用户";
        if(roleName==null || roleName=="" || roleName.contains(frontKeyword)){
            session.setAttribute("adminUser",false);
            return "redirect:/index/toFront";
        }else {
            session.setAttribute("adminUser",true);
            return "backIndex";
        }
    }

    public void addCookie(HttpServletResponse response,String username,String password,String rememberMe,String loginType){

        if (loginType.equals("email")){
            System.out.println("email cookie - -- -- -- - -- - ");
            Cookie cookie1=new Cookie("userEmail",username);
            Cookie cookie2=new Cookie("emailPassword",password);
            Cookie cookie3=new Cookie("emailRememberMe",rememberMe);
            cookie1.setMaxAge(30);
            cookie2.setMaxAge(30);
            cookie3.setMaxAge(30);
            response.addCookie(cookie1);
            response.addCookie(cookie2);
            response.addCookie(cookie3);
        }else if(loginType.equals("tel")){
            System.out.println("tel cookie - -- -- -- - -- - ");
            Cookie cookie1=new Cookie("userTel",username);
            Cookie cookie2=new Cookie("telPassword",password);
            Cookie cookie3=new Cookie("telRememberMe",rememberMe);
            cookie1.setMaxAge(30);
            cookie2.setMaxAge(30);
            cookie3.setMaxAge(30);
            response.addCookie(cookie1);
            response.addCookie(cookie2);
            response.addCookie(cookie3);
        }
    }

    @RequestMapping("/toForget")
    public String toForget(){
        return "forgetPassword";
    }

    @RequestMapping("/forget")
    @ResponseBody
    public String forgetPassword(String userEmail,String password){
        User user = userService.findUserByEmail(userEmail);
        if(user==null) {
            return "notFoundUser";
        }
        user.setPassword(password);
        int a = userService.saveOrUpdate(user);
        if(a>0) {
            return "ok";
        }
        else {
            return "error";
        }
    }

    @RequestMapping("getCheckCode")
    @ResponseBody
    public String getCheckCode(String email) {
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String message = "您的验证码：" + checkCode;
        System.out.println(checkCode);
        validateCheckCode = checkCode;
        try {
            System.out.println("------------" + checkCode);
            iMailService.sendSimpleMail(email, "重置密码", message);
        } catch (Exception e) {
            return "";
        }
        return checkCode;
    }
}